package com.ukao.steward.ui.logistics.EnterFactory;


import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.ScanCodeAdapter;
import com.ukao.steward.base.IAdapter;
import com.ukao.steward.base.IPage;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.base.PageWrapper;
import com.ukao.steward.bean.ScanCodeTabBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.dialog.BatchDialogFragment;
import com.ukao.steward.pesenter.logistics.ScanCodePesenter;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.view.logistics.ScanCodeView;
import com.ukao.steward.widget.ClearEditText;
import com.ukao.steward.widget.MyLRecyclerView;
import com.ukao.steward.widget.StateButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**

 */
public class ScanCodeFragment extends MvpFragment<ScanCodePesenter> implements ScanCodeView {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.start_work_btn)
    StateButton startWorkBtn;
    @BindView(R.id.sure_btn)
    StateButton sureBtn;
    @BindView(R.id.lrecycler_view)
    MyLRecyclerView lrecyclerView;
    Unbinder unbinder;
    @BindView(R.id.code)
    ClearEditText code;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.sweep_btn)
    ImageView sweepBtn;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private boolean isEnterFactory;
    private ScanCodeAdapter mScanCodeAdapter;
    private View view;
    private ArrayList<ScanCodeTabBean.ListBean> mData;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private PageWrapper mPageWrapper;
    private BatchDialogFragment mBatchFragment;
    private Handler mHandler = new Handler();
    private SoundPool mSoundPool;
    private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();
    private boolean loadFinish = false;
    private int currentPage = 1;
    private View mEmptyView;

    /**
     * @param isEnterFactory 是否是进厂订单订单进入
     * @param param2
     * @return
     */
    public static ScanCodeFragment newInstance(boolean isEnterFactory, String param2) {
        ScanCodeFragment fragment = new ScanCodeFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM1, isEnterFactory);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isEnterFactory = getArguments().getBoolean(ARG_PARAM1, false);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected void initView() {
        code.requestFocus();
         mData = new ArrayList<>();
         mEmptyView= view.findViewById(R.id.empty_view);
        initLinearRecyclerView(lrecyclerView);
        mScanCodeAdapter = new ScanCodeAdapter(_mActivity,mData,isEnterFactory);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mScanCodeAdapter);
        lrecyclerView.setAdapter(mLRecyclerViewAdapter);

        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {
                currentPage = geIndex;
                mvpPresenter.scanCodeTabele(isEnterFactory, geIndex, pageSize);


            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);
        page.setPageSize(20);
    }


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {
           mEmptyView.setVisibility(CheckUtils.isEmpty(data)?View.VISIBLE:View.GONE);
            mScanCodeAdapter.getDataList().clear();
            mScanCodeAdapter.setDataList(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            lrecyclerView.setLoadMoreEnabled(isNextLoad);

        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {

            mScanCodeAdapter.addAll(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            if (!isNextLoad) lrecyclerView.setNoMore(!isNextLoad);

        }
    };


    @Override
    protected ScanCodePesenter createPresenter() {
        return new ScanCodePesenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_scan_code, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            initSoundPool();
        } catch (Exception e) {
            e.printStackTrace();
        }
        initView();
        initListener();
    }

    @Override
    protected void initListener() {
        super.initListener();
        lrecyclerView.setOnRefreshListener(mOnRefreshListener);
        lrecyclerView.setOnLoadMoreListener(mOnLoadMoreListener);
        code.setOnEditorActionListener(mOnEditorActionListener);

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (currentPage == 1 && !loadFinish) lrecyclerView.forceToRefresh();


    }

    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
                mvpPresenter.receive(getText(code), isEnterFactory);
                setFoucus();
            }

            return false;
        }
    };

    void setFoucus() {
        code.setText("");
        code.requestFocus();
    }


    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {

            mPageWrapper.loadPage(true);
        }
    };
    private OnLoadMoreListener mOnLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            mPageWrapper.loadPage(false);
        }
    };


    @OnClick({R.id.start_work_btn, R.id.sure_btn, R.id.sweep_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_work_btn:
                deleteByOprType();
                break;
            case R.id.sure_btn:
                String strCode = getText(code);
                if (CheckUtils.isEmpty(strCode)) {
                    T.show(getString(R.string.please_enter_single_or_tracking_number));
                    return;
                }
                mvpPresenter.receive(strCode, isEnterFactory);

                break;
            case R.id.sweep_btn:

                Intent mIntent = ActivityUtils.JumpToBundleActivity(_mActivity);
                startActivityForResult(mIntent , Constant.REQUEST_CODE);
                break;

        }
    }




    void deleteByOprType() {
        mvpPresenter.deleteByOprType(isEnterFactory);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String  strCode=data.getStringExtra(Constant.ARG_PARAM1);
                    code.setText(strCode);
                    mvpPresenter.receive(strCode, isEnterFactory);
                    break;
            }
        }

    }

    /**
     * 接收成功
     */
    @Override
    public void receiveSuccceed() {
        mSoundPool.play(soundID.get(1), 1, 1, 0, 0, 1);
        lrecyclerView.forceToRefresh();

    }

    /**
     * 接收失敗
     * @param isAlarm  是否警报
     * @param msg
     */
    @Override
    public void receiveFail(boolean  isAlarm,String msg) {

        if (isAlarm){   mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1);   }
        mBatchFragment = BatchDialogFragment.createBuilder(getChildFragmentManager())
                .errorMsg(msg)
                .isReceiveSucceed(false)
                .show();

        mHandler.postDelayed(() -> {
            if (mBatchFragment != null){
                mBatchFragment.dismiss();   }

        }, 1500);
    }

    @Override
    public void scanCodeSucceed(ScanCodeTabBean mScanCodeData) {
        loadFinish = true;
        total.setText("已操作"+mScanCodeData.getTotal()+"单");
        mPageWrapper.addDataSource(mScanCodeData.getList(), mScanCodeData.getPages());
    }

    @Override
    public void receiveFinish() {
        setFoucus();
    }

    @Override
    public void deleteByOprSucceed() {
        if (lrecyclerView!=null)
        lrecyclerView.forceToRefresh();
    }


    /**
     * 加载完成
     */
    @Override
    public void loadSucceed() {
        lrecyclerView.refreshFinish();
    }


    private void initSoundPool()  throws Exception  {
        //当前系统的SDK版本大于等于21(Android 5.0)时

        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频数量
            builder.setMaxStreams(2);
            //AudioAttributes是一个封装音频各种属性的方法
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适的属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            //加载一个AudioAttributes
            builder.setAudioAttributes(attrBuilder.build());
            mSoundPool = builder.build();
        }
        //当系统的SDK版本小于21时
        else {//设置最多可容纳2个音频流，音频的品质为5
            mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
        }
        soundID.put(1, mSoundPool.load(_mActivity, R.raw.success, 1));
        soundID.put(2, mSoundPool.load(_mActivity, R.raw.worning, 1));  //需要捕获IO异常
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacksAndMessages(null);
        if (mSoundPool!=null){  mSoundPool.release();  }
        unbinder.unbind();
    }
}
